package com.linkin.homepage.base;


import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.linkin.homepage.R;
import com.linkin.homepage.base.loading.ILoadingAnimation;
import com.linkin.homepage.base.loading.LoadingView;
import com.linkin.homepage.base.viewmapping.ViewMapUtil;

import java.lang.ref.WeakReference;

public abstract class BaseFragment extends Fragment implements ILoadingAnimation {

    protected Context mContext;
    private FragmentHandler mFragmentHandler;
    private View rootView;

    private boolean mActive = false;
    private boolean mFragmentDestroyed = true;

    private String mTag = getClass().getSimpleName();

    public BaseFragment() {
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentHandler = new FragmentHandler(this);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentDestroyed = false;
        rootView = ViewMapUtil.inflate(this, inflater, container);
        initView(rootView);
        initLoadingView(rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        setActive();
    }

    @Override
    public void onPause() {
        super.onPause();
        setActive();
    }

    @Override
    public void onDestroyView() {
        mFragmentDestroyed = true;
        clear();
        getHandler().removeCallbacksAndMessages(null);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public boolean isFragmentDestroyed() {
        return mFragmentDestroyed;
    }

    public boolean isFragmentAlive() {
        return !isFragmentDestroyed();
    }

    public boolean isAlive() {
        return isFragmentAlive();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        setActive();
    }

    public View getRootView() {
        return rootView;
    }

    protected abstract void initView(View rootView);

    protected void initData() {
    }

    protected void refreshData() {
    }

    protected String getFragmentTag() {
        return mTag;
    }

    protected abstract void clear();

    private void setActive() {
        boolean active = isResumed() && getUserVisibleHint();
        if (mActive != active) {
            mActive = active;
            if (isAlive()) {
                onActive(active);
            }
        }
    }

    protected void onActive(boolean active) {
    }

    protected boolean isActive() {
        return mActive;
    }

    ////////////////////////////loading view 相关///////////////////////////////////////////////////////////////
    private LoadingView mLoadingView;
    private AnimationDrawable mLoadingDrawable;

    private void initLoadingView(View view) {
        mLoadingView = new LoadingView(view, v -> refreshData());
        mLoadingView.setLoadingAnimation(this);
        View v = view.findViewById(R.id.loading_img);
        if (v != null) {
            Drawable drawable = v.getBackground();
            if (drawable instanceof AnimationDrawable) {
                mLoadingDrawable = (AnimationDrawable) drawable;
            }
        }
        showNormal();
    }

    @Override
    public void startLoading() {
        if (mLoadingDrawable != null) {
            if (!mLoadingDrawable.isRunning()) {
                mLoadingDrawable.start();
            }
        }
    }

    @Override
    public void stopLoading() {
        if (mLoadingDrawable != null) {
            mLoadingDrawable.stop();
        }
    }

    protected void initNoDataView(String noDataStr, boolean clickable) {
        if (clickable) {
            mLoadingView.setNoDataTitle(noDataStr, v -> refreshData());
        } else {
            mLoadingView.setNoDataTitle(noDataStr, null);
        }
    }

    protected void setLoadingBackgroundColor(int color) {
        mLoadingView.setBackgroundColor(color);
    }

    /**
     * 显示原有视图
     */
    public void showNormal() {
        if (isAlive()) {
            mLoadingView.showLoading(0);
        }
    }

    /**
     * 显示加载中
     */
    public void showLoading() {
        if (isAlive()) {
            mLoadingView.showLoading(1);
        }
    }

    /**
     * 显示加载失败
     */
    public void showFailed() {
        if (isAlive()) {
            mLoadingView.showLoading(2);
        }
    }

    /**
     * 显示无内容
     */
    public void showNoData() {
        if (isAlive()) {
            mLoadingView.showLoading(3);
        }
    }

    public boolean isShowingNormal() {
        return mLoadingView.isShowingNormal();
    }

    public boolean isShowingLoading() {
        return mLoadingView.isShowingLoading();
    }

    public boolean isShowingFailed() {
        return mLoadingView.isShowingFailed();
    }

    public boolean isShowingNoData() {
        return mLoadingView.isShowingNoData();
    }

    ////////////////////////////Handler 相关///////////////////////////////////////////////////////////////

    /**
     * 获取handler
     */
    protected Handler getHandler() {
        return mFragmentHandler;
    }

    protected void handleMessage(Message msg) {
    }

    protected static class FragmentHandler extends Handler {

        private WeakReference<BaseFragment> mFragmentWeakReference;

        FragmentHandler(BaseFragment fragment) {
            mFragmentWeakReference = new WeakReference<>(fragment);
        }

        @Override
        public void dispatchMessage(Message msg) {
            BaseFragment fragment = mFragmentWeakReference.get();
            if (fragment != null && fragment.isFragmentAlive()) {
                super.dispatchMessage(msg);
            }
        }

        @Override
        public void handleMessage(Message msg) {
            BaseFragment fragment = mFragmentWeakReference.get();
            if (fragment != null && fragment.isFragmentAlive()) {
                fragment.handleMessage(msg);
            }
        }
    }
}
